﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Coevery.ViewModel;
using System.Windows.Navigation;
using Coevery.ViewModel.EntityDataService;
using Microsoft.Phone.Shell;

namespace Coevery.PhoneApp
{
    public partial class Comment : PhoneApplicationPage
    {
        private string _action;
        private string _objectType;
        private string _objectId;

        public Comment()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            NavigationContext.QueryString.TryGetValue("Action", out _action);
            NavigationContext.QueryString.TryGetValue("ObjectType", out _objectType);
            NavigationContext.QueryString.TryGetValue("ObjectId", out _objectId);

            if(_action == "Edit")
            {
                var note = PhoneApplicationService.Current.State["Note"] as Note;
                if (note != null)
                {
                    subject.Text = note.Subject;
                    noteText.Text = note.NoteText;
                }
            }
        }

        private void Save_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(subject.Text) || string.IsNullOrEmpty(noteText.Text))
            {
                MessageBox.Show("The subject and description cannot be empty.");
            }
            else
            {
                SaveChanges();
            }
        }

        public void SaveChanges()
        {
            if (_action == "Add")
            {
                var objectId = new Guid(_objectId);
                var note = new Note
                               {
                                   NoteId = Guid.NewGuid(),
                                   ObjectId = objectId,
                                   ObjectType = _objectType,
                                   CreatedById = Guid.Parse(App.Setting["UserId"].ToString()),
                                   ModifiedById = Guid.Parse(App.Setting["UserId"].ToString()),
                                   Subject = subject.Text,
                                   NoteText = noteText.Text,
                                   IsDeleted = false,
                                   VersionNumber = BitConverter.GetBytes(DateTime.Now.ToOADate())
                               };
                note.CreatedOn = note.ModifiedOn = DateTime.Now;
                BaseViewModel.Context.AddToNotes(note);
                BaseViewModel.Context.BeginSaveChanges(OnChangesSaved, BaseViewModel.Context);
            }
            else
            {
                var note = PhoneApplicationService.Current.State["Note"] as Note;
                note.Subject = subject.Text;
                note.NoteText = noteText.Text;
                note.ModifiedOn = DateTime.Now;
                note.ModifiedById = Guid.Parse(App.Setting["UserId"].ToString());
                BaseViewModel.Context.UpdateObject(note);
                BaseViewModel.Context.BeginSaveChanges(OnChangesSaved, BaseViewModel.Context);
            }
        }

        private void OnChangesSaved(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
                                       {
                                           BaseViewModel.Context.EndSaveChanges(result);
                                           Dispatcher.BeginInvoke(
                                               () =>
                                               NavigationService.GoBack());
                                       });
        }
    }
}